//
//  LWButton.m
//  Assistive Touch
//
//  Created by Roman on 16/11/17.
//  Copyright © 2016年 Roman. All rights reserved.
//

#import "LWButton.h"
@class HomeViewController;

@interface LWButton ()

@property (nonatomic, assign) CGPoint beginPoint;

@end

@implementation LWButton



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
   [super touchesBegan:touches withEvent:event];
    //1.取出触摸点
    UITouch *touch = [touches anyObject];
    
    _beginPoint = [touch locationInView:self];
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"button" object:nil];

}



- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesMoved:touches withEvent:event];
    //1.取出触摸点
    UITouch *touch = [touches anyObject];
    
    CGPoint currentPoint = [touch locationInView:self];
    
    //计算偏移量
    CGFloat X = currentPoint.x - _beginPoint.x;
    CGFloat Y = currentPoint.y - _beginPoint.y;
    
    self.center = CGPointMake(self.center.x + X, self.center.y +Y);
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
    [super touchesEnded:touches withEvent:event];
    //获取按钮的frame;
    CGFloat buttonX = self.frame.origin.x;
    CGFloat buttonY = self.frame.origin.y;
    CGFloat buttonW = self.frame.size.width;
    CGFloat buttonH = self.frame.size.height;
    
    //屏幕的宽高
    CGFloat screenW = [UIScreen mainScreen].bounds.size.width;
    CGFloat screenH = [UIScreen mainScreen].bounds.size.height;
    
    //获取按钮距离四个边的距离
    CGFloat marginLeft  = buttonX;
    
    CGFloat marginRight = screenW - buttonX -buttonW;
    
    CGFloat marginTop =  buttonY;
    
    CGFloat marginBotton = screenH - buttonY - buttonH;
    
    [UIView animateWithDuration:0.25 animations:^{
        //1. 上边, 按钮向上靠拢
        if (marginTop < 60) {
            
            self.frame = CGRectMake(marginLeft < marginRight ? (marginLeft < 5 ? 5 : buttonX): (marginRight < 5 ? (screenW - buttonW - 5) : buttonX ),5 , buttonW, buttonH);
        }
        
        //2. 下边, 按钮向下靠
        
        else if (marginBotton < 60) {
            self.frame = CGRectMake(marginLeft < marginRight ?(marginLeft < 5 ? 5 :buttonX):(marginRight <5 ?(screenW - buttonW - 5) :buttonX), screenH - 5 - buttonH, buttonW, buttonH);
        }
        
        // 3 .其余的情况
        else
        {
            self.frame = CGRectMake(marginLeft < marginRight ? 5 :(screenW - buttonW - 5), buttonY, buttonW, buttonH);
        }
        
    }];

}


@end
